import Axios from 'axios'
import { showToast ,closeToast, showLoadingToast} from 'vant';
import {useUserStore} from "../store/user";
import router from "@/router";

const baseURL = import.meta.env.VITE_BASEURL
const axios = Axios.create({
    // baseURL,
    baseURL: baseURL,
    timeout: 1000*10*60 // 请求超时 20s
})
// 前置拦截器（发起请求之前的拦截）
axios.interceptors.request.use(
    (response) => {
         
        // const store  = useUserStore()
        // const token = store?.token || ''
        // 应该在这里做toastloading的 但是从pc端复制的  懒得改了
        let  token = localStorage.getItem('user_token')
        if (token && !token.includes('Bearer')) { 
            token = 'Bearer ' + token
        }
        response.headers['Authorization'] =  token
        response.params = {
			_t: Date.parse(new Date() + '') / 1000,
			...response.params,
		};


        return response
    },
    (error) => {
        console.log(error);
        return Promise.reject(error)
    }
)

// 后置拦截器（获取到响应时的拦截）
axios.interceptors.response.use(
    async (response) => {
        console.log(response);
        const code = response.data.code as number
        const dontShowMessageApiList = ['/api/v1/funds/game/exchange/records']
       
        if (code  != 200) {
            console.error(response.data.message)
            if (dontShowMessageApiList.includes(response.config?.url)) {
                //这个白名单的就不显示报错

            }else {
                // setTimeout(()=> {
                //     showToast(response.data.message);
                // }, 500)
            }
            return Promise.reject()
        }
        closeToast(true)
        return response.data.data
    },
    (error) => {
        closeToast(true)
        return Promise.reject(error)
    }
)

export default axios
function request<T=any , B = any>(url:string, item?:B, loading:boolean = false): Promise<T> {
    if (loading) {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
          });
    }
    return axios.post(url, item)

     
}
function requestGet<T=any ,>(url:string , params?: any ,responseType: any = ''): Promise<T> {
   
    return axios.get(url,{params,responseType})
}

function requestDelete<T=any>(url:string , params?: any ,responseType: any = ''): Promise<T> {
    return axios.delete(url, { params, responseType })
}
export {request, requestGet, requestDelete}
